// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.


const { fstat } = require("fs");

function btnGroup2 (){
  let html =
    '<a href="#!" class="btn btn-xs btn-info m-r-5 html-btn" title="显示内容" data-toggle="tooltip"><i class="mdi mdi-comment-processing-outline"></i></a>'+
    '<a href="#!" class="btn btn-xs btn-primary m-r-5 open-btn" title="打开附件" data-toggle="tooltip"><i class="mdi mdi-folder-open"></i></a>';
  return html;
}

const EmailTableOption = {
  classes: 'table table-bordered table-hover table-striped fix-table',
  dataType : 'json',        // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
  uniqueId: 'id',
  idField: 'id',             // 每行的唯一标识字段
//  toolbar: '#toolbar',       // 工具按钮容器
  showColumns: false,         // 是否显示所有的列
  showRefresh: true,         // 是否显示刷新按钮
  pagination: true,                    // 是否显示分页
  sortOrder: "asc",                    // 排序方式                                  // 传递参数
  sidePagination: "client",            // 分页方式：client客户端分页，server服务端分页
  pageNumber: 1,                       // 初始化加载第一页，默认第一页
  pageSize: 7,                        // 每页的记录行数
  pageList: [7],         // 可供选择的每页的行数
  search: true,                      // 是否显示表格搜索，此搜索是客户端搜索
  columns: [// 是否排序 
    { field: 'id', title: 'ID', sortable: true, width: 60 },
    { field: 'subject', title: '主题', sortable: true, width: 180 },
    { field: 'date', title: '日期', sortable: true, width: 160 }, 
    { field: 'html', title: '正文（简略）'}, 
    { field: 'file', title: '附件', width: 160},
    { field: 'operate', title: '操作', formatter: btnGroup2, width: 100,  // 自定义方法
      events: {
        'click .html-btn': function (event, value, row, index) {
          if( row.id !== '') show_email_html( row )
        },
        'click .open-btn': function (event, value, row, index) {
          if( row.file !== '') email_down_file( row, index )
        }
      }
  }],
  onLoadSuccess: function(data){
      $("[data-toggle='tooltip']").tooltip();
  }
}

function email_down_file(row){
  const path = require('path')
  const fs = require('fs')
  const cp = require('child_process')
  const fPath = path.join(path.dirname(remote.getGlobal('fPath')), row.id)

  fs.stat(fPath, function(error, stats){
    if(stats.isDirectory()) {
      //“%SystemRoot%＼explorer.exe /e,h:＼user”
      if(process.platform === 'win32') cp.exec(`%SystemRoot%\\explorer.exe /e,${fPath}`);
      else cp.exec(`open "${fPath}"`);
    }
  })
  
  //dialog.showOpenDialog
}

function show_email_html(row){
  const html = row.html + '<br/>附件：<br/>' + row.file
  $.confirm({
    title: '邮件正文内容',
    content: html,
    buttons: {
      cancel: {
          text: '关闭'
      },
    },
    onContentReady: function () {
      var jc = this;
      this.$content.find('form').on('submit', function (e) {
          e.preventDefault();
          jc.$$formSubmit.trigger('click');
      });
    }
  });
}

$('#email_table').bootstrapTable(EmailTableOption);

$("#load_account_email_btn").click(function(){
  const account = $("#account_sel").val()
  const pwd = $("#account_pwd").val()
  const date = $("#account_date").val()

  if(account === '' || pwd === '' || date === '') {
    $.alert('请选择账号，输入账号对应访问密码和邮件查询开始日期再载入邮件！')
    return
  }
  ipcRenderer.send('del_store', account)

  const accounts = store.get('v1.accounts')
  let findAccount = false
  let findPwd = false
  accounts.forEach( item=>{
    if(item.email === account) {
      findAccount = true
      findPwd = item.password === pwd
    }
  })
  
  if(!findAccount) {
    $.alert('邮箱账号不正确！')
    return
  }

  if(!findPwd){
    $.alert('访问密码不匹配！')
    return  
  }

  $(this).button('loading')
  lightyear.loading('show');

  
  ipcRenderer.send('load_email', {account, date})
})

function loadEmailTable(account){
  const json = store.get(account) || []
//  const json = remote.getGlobal(account)

  const data = []
  json.forEach( item=> {
    data.push({
      id: item.id,
      subject: item.subject,
      date: item.date,
      html: item.text,
      file: item.files ? item.files.join(',') : ''
    })
  })
  // for(let key in json){
  //   if(json[key]) {
  //     data.push({
  //       id: key,
  //       subject: json[key].subject,
  //       date: dateFormat('YYYY-mm-dd HH:MM', json[key].date),
  //       html: json[key].text,
  //       file: json[key].files ? json[key].files.join(',') : ''
  //     })
  //   }
  // }
  console.log('json', json)
  console.log('data', data)
  $('#email_table').bootstrapTable('destroy');
  $('#email_table').bootstrapTable(EmailTableOption);
  $('#email_table').bootstrapTable('load', data)
}

ipcRenderer.on('load_email_step', function(event, arg){

  loadEmailTable(arg)
  //const json = remote.getGlobal(account)

  // console.log('step', new Date(), id, json[id])
  // if(json[id] && json[id].text!==''){
  //   $('#email_table').bootstrapTable('prepend', {id, subject: json[id].subject, 
  //     date: dateFormat('YYYY-mm-dd HH:MM', json[id].date),
  //     html: json[id].text, file: json[id].files.join(' '),
  //   });
  // }
})

ipcRenderer.on('load_email_replay', function(event, arg){
  $("#load_account_email_btn").button('reset')
  lightyear.loading('hide');

  if(arg.type==='error'){
    $.alert('发生了错误：'+ arg.msg)
  }else if(arg.type==='ok') {
    $.alert('邮件加载完毕！')
    loadEmailTable(arg.data)
  }
})